package com.base.library.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * Created by enlong on 2016/11/28.
 */

public class GlideCircleTransform extends BitmapTransformation {
    protected  int margin;
    private int margin_Color;

    public GlideCircleTransform(Context context, int margin, int margin_Color) {
        super(context);
        this.margin = margin;
        this.margin_Color = margin_Color;

    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap source, int outWidth, int outHeight) {


        if (null == source) return null;


        int size = Math.min(source.getWidth(), source.getHeight());
        int o_size = Math.min(outHeight, outWidth);
        o_size = (0 >= o_size) ? size : o_size;

        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;


        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

        int real = o_size ;
        Bitmap result = pool.get(real, real, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(real, real, Bitmap.Config.ARGB_8888);
        }


        Canvas canvas = new Canvas(result);
        canvas.drawColor(Color.TRANSPARENT);
        Paint paint = new Paint();
        BitmapShader bitmapShader = new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);

        paint.setAntiAlias(true);

        Matrix matrix = new Matrix();
        bitmapShader.getLocalMatrix(matrix);
        float scale = o_size * 1.0f / size ;
        matrix.setScale( scale,scale) ;
        bitmapShader.setLocalMatrix(matrix);

        paint.setShader(bitmapShader);

        float r = real / 2;
        int realMagin = (scale > 1) ? (int) (margin / scale) : margin;
        if(realMagin > 0) {
            Paint p = new Paint();
            p.setAntiAlias(true);
            p.setColor(margin_Color);
            p.setStyle(Paint.Style.FILL);


            canvas.drawCircle(r, r, r, p);
        }
        canvas.drawCircle(r, r, r - realMagin, paint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return result;
    }

    @Override
    public String getId() {
        return getClass().getName() + margin + margin_Color;
    }
}
